<?php
/**
 * Created by PhpStorm.
 * User: FoxxxZhu
 * Date: 2018/8/6
 * Time: 9:49
 */
namespace Forxx\Api;

use Forxx\Api\Utils;
use Lavender\Core;
use Lavender\Exception;
use Lavender\WebPage;

/**
 * Class base_service
 * @package App\Action\Service
 * @property \Lavender\WebPage $controller
 */
class InnerCall
{
    protected $controller = null;
    protected $errorMsg = "";
    CONST LOG_LEVEL_NOTICE = 1;
    CONST LOG_LEVEL_SUCCESS = 2;
    CONST LOG_LEVEL_WARNING = 3;
    CONST LOG_LEVEL_ERROR = 4;
    CONST LOG_LEVEL_DANGER = 5;

    protected function __construct(WebPage $ctrl){
        $this->controller = $ctrl;
    }

    public static function instance(WebPage $ctrl){
        return new Static($ctrl);
    }

    public function setApiHost($apiHost){
        $this->apiHost = $apiHost;
        return $this;
    }

    public function setApiHostKey($apiHostKey){
        $this->apiHostKey = $apiHostKey;
        return $this;
    }

    public function getBaseApiHost($hostKey){
        $hosts = Core::get_config("const","host");
        if(isset($hosts[$hostKey])){
            return $hosts[$hostKey];
        }
        return "";
    }

    public function getFullUrlPath($path)
    {
        if(substr($path,0,4) == "http"){
            return $path;
        }
        $module = "api";
        $ret = preg_match("/^{{(.+)}}/",$path,$match);
        if(isset($match[1])){
            $module = $match[1];
        }
        $baseUrl = $this->getBaseApiHost($module);
        if(empty($baseUrl)){
            throw new  Exception("inner api host key '{$module}' not set!");
        }
        $realPath =  str_replace("{{".$module."}}","",$path);
        return $baseUrl.$realPath;
    }

    public function post($path, array $postData, $timeout = 30)
    {
        $url = $this->getFullUrlPath($path);
        $ip = $this->controller->get_client_ip();
        $header = [
            'X-Forwarded-For:'.$ip,
            'HTTP_CLIENT_IP:'.$ip,
            'X-Real-Ip:'.$ip,
            'APP_ID:'.L_APP_NAME,
        ];
        return Utils::httpJsonp($url,$postData,$timeout,$header);
    }

    public function ajaxPost($path,array $postData){
        $url = $this->getFullUrlPath($path);
        $ip = $this->controller->get_client_ip();
        $header = [
            'X-Forwarded-For:'.$ip,
            'HTTP_CLIENT_IP:'.$ip,
            'X-Real-Ip:'.$ip,
            'APP_ID:'.L_APP_NAME,
        ];
        Core::log("api_call_error",date("Y-m-d H:i:s")."\n post url:\t {$url} \n data: \n ".json_encode($postData,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT)." \n\n");
        Utils::ajaxHttp($url,json_encode($postData,JSON_UNESCAPED_UNICODE),100,$header);
    }

    public function log($message,$level = self::LOG_LEVEL_NOTICE,$path= "/user/add_log",$type = null,$ip = null,$uid = 0){
        if(is_null($type)){
            $type = $this->controller->get_module_name()."/".$this->controller->get_action_name();
            if(strlen($type) > 100){
                $type = substr($type,0,100);
            }
        }
        if(is_null($ip)){
            $ip = $this->controller->get_client_ip();
        }
        if(empty($uid)){
            $uid = $this->controller->get_uid();
        }
        $this->ajaxPost($path,[
            'remark'=>$message,
            'type'=>$type,
            'level' => $level,
            'ip'=>$ip,
            'uid'=>$uid,
        ]);
    }

    public function getLastError(){
        return $this->errorMsg;
    }

    public function getData($path, array $postData,$autolog = false){
        $this->errorMsg = "";
        $data = $this->post($path,$postData);
        $url = $this->getFullUrlPath($path);

        if(is_array($data) && isset($data['code']) && $data['code'] == 0 && isset($data['data']))
        {
            return $data['data'];
        }
        else{
            if(defined('L_DEBUG') && L_DEBUG){
                Core::log("api_call_error",date("Y-m-d H:i:s")."\n url:{$url} \n postData: ".json_encode($postData,JSON_UNESCAPED_UNICODE)."\n result:".json_encode($data,JSON_UNESCAPED_UNICODE)." \n\n");
            }
            else{
                Core::log("api_call_error",date("Y-m-d H:i:s")."\n post url:{$url} \n result:".json_encode($data,JSON_UNESCAPED_UNICODE)."\n\n");
            }

            if(isset($data['msg'])){
                $this->errorMsg = $data['msg'];
            }
            else{
                $this->errorMsg = "未知错误: ".json_encode($data,JSON_UNESCAPED_UNICODE);
            }
            if($autolog){
                $message = "调用接口[".$path."] 失败. 返回: ".json_encode($data,JSON_UNESCAPED_UNICODE);
                if(!empty($this->errorMsg)){
                    $message .= " 错误参考:".$this->errorMsg;
                }
                $this->log($message,self::LOG_LEVEL_ERROR);
            }
        }
        return null;
    }
}
